package com.e_manager.soft.emanager.controller;

import com.alibaba.fastjson.JSON;
import com.e_manager.soft.emanager.annotation.BaseController;
import com.e_manager.soft.emanager.annotation.CurrentUser;
import com.e_manager.soft.emanager.entity.User;
import com.e_manager.soft.emanager.resultMsg.ResultConstant;
import com.e_manager.soft.emanager.resultMsg.ResultInfo;
import com.e_manager.soft.emanager.service.UserService;
import com.e_manager.soft.emanager.util.HttpClientUtil;
import com.e_manager.soft.emanager.util.UuidUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author : lip[lip4051@163.com]
 * @create : 2018/3/15 0015 下午 1:02
 */
@BaseController
@Api(value = "注册", description = "用户注册")
public class RegisterControoler {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Value("${appid}")
    private String appid;
    @Value("${url}")
    private String postUrl;
    @Value("${signature}")
    private String signature;
    @Value("${project}")
    private String project;
    @Value("${time}")
    private String time;
    @Value("${projects}")
    private String projects;
    @Value("${link}")
    private String link;
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    /*@ResponseBody*/
    public ResultInfo<?> register(@RequestParam("userName") String userName, @RequestParam("loginPwd") String pwd, @RequestParam("phone") String phone, @RequestParam("validateCode") String code,
                                  @RequestParam("address") String address, @RequestParam("propertyInsurance") String propertyInsurance) {
        //检查用户是否存在
        ResultInfo info = new ResultInfo();
        User u = userService.getByUserName(phone);
        if (u != null) {
            info.setMsg(ResultConstant.USER_ALREADY_EXISTS.getMessage());
            info.setCode(ResultConstant.USER_ALREADY_EXISTS.getCode());
            return info;
        }
        User user = new User();
        user.setUserID(UuidUtil.get32UUID());
        user.setLoginName(phone);
        user.setLoginPwd(pwd);
        user.setPhone(phone);
        user.setUserName(userName);
        user.setCreateUser(user.getUserID());
        user.setAddress(address);
        user.setPropertyInsurance(propertyInsurance);
        if (checkCode(code, phone)) {
            userService.inserteUser(user);
            info.setMsg(ResultConstant.SUCCESS.getMessage());
            info.setCode(ResultConstant.SUCCESS.getCode());
            return info;
        } else {
            info.setMsg(ResultConstant.CHECK_CODE_FAIL.getMessage());
            info.setCode(ResultConstant.CHECK_CODE_FAIL.getCode());
            return info;
        }
    }

    public boolean checkCode(String vcode, String phone) {
        String source = stringRedisTemplate.opsForValue().get(phone);
        if (source != null && source.equals(vcode)) {
            stringRedisTemplate.opsForValue().getOperations().delete(phone);
            return true;
        } else {
            return false;
        }
    }

    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    @PostMapping(value = "/codes", produces = {"application/json;charset=utf-8"})
    public ResultInfo<?> getCode(@RequestParam("phone") String phone) {
        //初始化对象
        ResultInfo info = new ResultInfo();
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String> varMap = new HashMap<String, String>();
        //随机生成6位验证码
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        try {
            //替换模板的变量
            varMap.put("code", verifyCode);
            //时间
            varMap.put("time", time);
            //短信url
            String url = postUrl;
            //短信id
            map.put("appid", appid);
            //接收人电话
            map.put("to", phone);
            //短信模板标识
            map.put("project", project);
            //动态改变模板里的参数
            map.put("vars", JSON.toJSONString(varMap));
            //短信明文签名
            map.put("signature", signature);
            //请求
            HttpClientUtil.doPostJson(url, JSON.toJSONString(map));
            stringRedisTemplate.opsForValue().set(phone, verifyCode);
            info.setMsg(ResultConstant.SUCCESS.getMessage());
            info.setCode(ResultConstant.SUCCESS.getCode());
        } catch (Exception e) {
            info.setMsg(ResultConstant.CHECK_CODE_FAIL.getMessage());
            info.setCode(ResultConstant.CHECK_CODE_FAIL.getCode());
        }
        return info;

    }

    @ApiOperation(value = "推送下载app连接", notes = "推送下载app连接")
    @PostMapping(value = "/appDown", produces = {"application/json;charset=utf-8"})
    public ResultInfo<?> appDown(@RequestParam("phone") String phone, @CurrentUser User iuser) {
        //初始化对象
        ResultInfo info = new ResultInfo();
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String> varMap = new HashMap<String, String>();
        User user = userService.getByUserInfor(iuser.getUserID());
        try {
            //替换模板的变量
            varMap.put("userName", user.getUserName());
            //时间
            varMap.put("link", link);
            //短信url
            String url = postUrl;
            //短信id
            map.put("appid", appid);
            //接收人电话
            map.put("to", phone);
            //短信模板标识
            map.put("project", projects);
            //动态改变模板里的参数
            map.put("vars", JSON.toJSONString(varMap));
            //短信明文签名
            map.put("signature", signature);
            //请求
            HttpClientUtil.doPostJson(url, JSON.toJSONString(map));
            info.setMsg(ResultConstant.SUCCESS.getMessage());
            info.setCode(ResultConstant.SUCCESS.getCode());
        } catch (Exception e) {
            info.setMsg(ResultConstant.CHECK_CODE_FAIL.getMessage());
            info.setCode(ResultConstant.CHECK_CODE_FAIL.getCode());
        }
        return info;

    }

}
